package ae.generator;

import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.Types;
import java.util.Map;

/**
 * @author: zxm
 * @date: 2025/9/4
 */
public class GenerateUtil {

    /**
     * 将表名转换为类名（下划线转驼峰，首字母大写）
     */
    public static String convertToClassName(String tableName) {
        StringBuilder className = new StringBuilder();
        boolean nextUpperCase = false;
        for (char c : tableName.toCharArray()) {
            if (c == '_') {
                nextUpperCase = true;
            } else {
                if (nextUpperCase) {
                    className.append(Character.toUpperCase(c));
                    nextUpperCase = false;
                } else {
                    // 首字母大写
                    if (className.isEmpty()) {
                        className.append(Character.toUpperCase(c));
                    } else {
                        className.append(c);
                    }
                }
            }
        }
        return className.toString();
    }

    /**
     * 首字母转为小写
     */
    public static String firstLetterToLower(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        return Character.toLowerCase(str.charAt(0)) + str.substring(1);
    }

    /**
     * 首字母转为大写
     */
    public static String firstLetterToUpper(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        return Character.toUpperCase(str.charAt(0)) + str.substring(1);
    }

    /**
     * 读取模板文件内容
     */
    public static String readTemplate(String templateFileName) throws IOException {
        try (InputStream is = new FileInputStream(getResourceUrl(templateFileName))) {
            try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
                StringBuilder content = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    content.append(line).append(System.lineSeparator());
                }
                return content.toString();
            }
        }
    }

    /**
     * 替换模板中的变量
     */
    public static String replaceTemplateVariables(String template, Map<String, String> dataModel) {
        String result = template;
        for (Map.Entry<String, String> entry : dataModel.entrySet()) {
            String placeholder = "${" + entry.getKey() + "}";
            result = result.replace(placeholder, entry.getValue() != null ? entry.getValue() : "");
        }
        return result;
    }


    /**
     * 获取资源路径
     * @param resourceName 资源名
     * @return 资源的URL
     */
    public static String getResourceUrl(String resourceName) {
        try {
            URL resourceUrl = GenerateUtil.class.getClassLoader().getResource(resourceName);
            assert resourceUrl != null;
            return new File(resourceUrl.toURI()).getAbsolutePath();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取包对应的目录路径
     */
    public static String getPackagePath(String basePackage,String subPackage) {
        return (basePackage + "." + subPackage).replace(".", "/");
    }

    /**
     * 将驼峰式命名转换为连字符分隔的小写形式
     * @param camelCase 驼峰式命名的字符串
     * @return 连字符分隔的小写字符串
     */
    public static String convertCamelCase(String camelCase) {
        if (camelCase == null || camelCase.isEmpty()) {
            return camelCase;
        }

        StringBuilder result = new StringBuilder();
        // 处理第一个字符，直接转为小写
        result.append(Character.toLowerCase(camelCase.charAt(0)));

        // 遍历剩余字符
        for (int i = 1; i < camelCase.length(); i++) {
            char currentChar = camelCase.charAt(i);
            // 如果是大写字母，先加连字符再转小写
            if (Character.isUpperCase(currentChar)) {
                result.append('-');
                result.append(Character.toLowerCase(currentChar));
            } else {
                // 非大写字母直接添加
                result.append(currentChar);
            }
        }

        return result.toString();
    }

    /**
     * 下划线转驼峰
     */
    public static String convertToCamelCase(String str) {

        StringBuilder result = new StringBuilder();
        if (str == null || str.isEmpty()) {
            return "";
        }
        // 是否需要大写下一个字符
        boolean capitalizeNext = false;
        for (char c : str.toCharArray()) {
            if (c == '_') {
                capitalizeNext = true;
            } else {
                if (capitalizeNext) {
                    result.append(Character.toUpperCase(c));
                    capitalizeNext = false;
                } else {
                    result.append(Character.toLowerCase(c));
                }
            }
        }
        return result.toString();
    }

    /**
     * 将数据库类型转换为Java类型
     */
    public static String getJavaType(int dataType) {
        return switch (dataType) {
            case Types.INTEGER, Types.SMALLINT -> "Integer";
            case Types.BIGINT -> "Long";
            case Types.FLOAT, Types.DOUBLE, Types.REAL -> "Double";
            case Types.DECIMAL, Types.NUMERIC -> "BigDecimal";
            case Types.CHAR, Types.VARCHAR, Types.LONGVARCHAR -> "String";
            case Types.DATE, Types.TIME, Types.TIMESTAMP -> "Date";
            case Types.BOOLEAN -> "Boolean";
            case Types.BLOB -> "byte[]";
            default -> "String";
        };
    }

}
